<template> 
  <el-card class="form-container" shadow="never">
    <el-form :model="subject" :rules="rules" ref="subjectFrom" label-width="80px">
      <el-form-item label="标题：" prop="name">
        <el-input v-model="subject.name"></el-input>
      </el-form-item>
      <el-form-item label="图片：" prop="picUrl">
        <single-upload v-model="subject.picUrl" tip="请上传 350*216px 的图片"></single-upload>
      </el-form-item>
      <el-form-item label="类型：" prop="type">
        <el-radio v-model="subject.type" label="1" size="medium">产品详情</el-radio>
        <el-tooltip class="item" effect="dark" content="需要在本仓库下的推荐版块中维护内容后，再进行关联" placement="top">
          <el-radio v-model="subject.type" label="2" size="medium">推荐版块</el-radio>
        </el-tooltip>
        <el-radio v-model="subject.type" label="3" size="medium">产品列表</el-radio>
        <el-radio v-model="subject.type" label="4" size="medium">自定义页面</el-radio>
      </el-form-item>
      
      <el-form-item label="关联商品" required v-if="subject.type == 1 ">
        <el-table v-if="subject.productSingle.length>0" ref="productRelationTable" :data="subject.productSingle"
                style="width: 100%;" border>
          <el-table-column label="编号" width="100" align="center">
            <template slot-scope="scope">{{scope.row.id}}</template>
          </el-table-column>
          <el-table-column label="商品名称" width="200" align="center">
            <template slot-scope="scope">{{scope.row.name}}</template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center" >
            <template slot-scope="scope">
              <el-button size="mini"
                        type="text"
                        @click="handleDeleteProduct(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button size="mini" class="btn-add" v-if="subject.productSingle.length == 0"  @click="handleSelectProduct()" style="margin-left: 20px">添加关联商品</el-button>
      </el-form-item>
      <el-form-item label="关联商品" required v-if="subject.type == 3">
        <el-table ref="productRelationTable" :data="subject.productList"
                style="width: 100%;" border v-if="subject.productList.length>0">
          <el-table-column label="编号" width="80" align="center">
            <template slot-scope="scope">{{scope.row.id}}</template>
          </el-table-column>
          <el-table-column label="商品名称" width="200" align="center">
            <template slot-scope="scope">{{scope.row.name}}</template>
          </el-table-column>
          <el-table-column label="排序" width="150" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.sort"></el-input></template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleDeleteProduct(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button size="mini" class="btn-add" @click="handleSelectProduct()" style="margin-left: 20px">添加关联商品</el-button>
      </el-form-item>
      <el-form-item label="推荐版块" required v-if="subject.type == 2" prop="blocks">
        <el-table ref="productRelationTable" :data="subject.blocks"
                style="width: 100%;" border v-if="subject.blocks.length>0">
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="板块名称" width="276" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
         <el-table-column label="操作" width="80" align="center" >
           <!-- v-if="isEdit" -->
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleDeleteBlock(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
        </el-table>
        <el-button size="mini" class="btn-add" @click="handleSelectBlock()" style="margin-left: 20px">添加关联板块</el-button>
      </el-form-item>
      <el-form-item label="自定义：" prop="redirectUrl" v-if="subject.type == 4">
        <!-- <el-input v-model="subject.redirectUrl" placeholder="需要在小程序后台设置域名，谨慎配置"></el-input> -->
        <tinymce :width="580" :height="300" v-model="subject.redirectUrl"></tinymce>
      </el-form-item>

       <el-form-item label="排序">
        <el-input v-model="subject.sort"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('subjectFrom')">提交</el-button>
        <el-button v-if="!isEdit" @click="resetForm('subjectFrom')">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 选择商品的弹窗 -->
    <el-dialog title="选择商品" :visible.sync="selectDialogVisible" width="50%">
      <el-input v-model="dialogData.listQuery.keyword"
                style="width: 250px;margin-bottom: 20px"
                size="small"
                placeholder="商品名称搜索">
        <el-button slot="append" icon="el-icon-search" @click="handleSelectSearch()">点击搜索</el-button>
      </el-input>
      <el-table :data="dialogData.list"
                @selection-change="handleDialogSelectionChange" border>
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="商品图片" align="center">
          <template slot-scope="scope">
            <img style="max-width: 260px;max-height:60px;" :src="scope.row.pic" />
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column label="货号" width="160" align="center">
          <template slot-scope="scope">NO.{{scope.row.productSn}}</template>
        </el-table-column>
        <el-table-column label="价格" width="120" align="center">
          <template slot-scope="scope">{{moneyIcon}}{{scope.row.price}}</template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleDialogSizeChange"
          @current-change="handleDialogCurrentChange"
          layout="prev, pager, next"
          :current-page.sync="dialogData.listQuery.pageNum"
          :page-size="dialogData.listQuery.pageSize"
          :page-sizes="[5,10,15]"
          :total="dialogData.total">
        </el-pagination>
      </div>
      <div style="clear: both;"></div>
      <div slot="footer">
        <el-button  size="small" @click="selectDialogVisible = false">取 消</el-button>
        <el-button  size="small" type="primary" @click="handleSelectDialogConfirm()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 选择板块的弹窗 -->
     <el-dialog title="选择板块" :visible.sync="selectBlockDialog" width="50%">
      <el-table :data="recommendBlocks"
                @selection-change="handleBlockDialogSelectionChange" border>
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="板块名称" align="center">
          <template slot-scope="scope">{{scope.row.name}}</template>
        </el-table-column>
        <el-table-column label="背景图片" width="360" align="center">
          <template slot-scope="scope">
            <img style="height: 80px" :src="scope.row.pic">
          </template>
        </el-table-column>
      </el-table>
      <div style="clear: both;"></div>
      <div slot="footer">
        <el-button  size="small" @click="selectBlockDialog = false;">取 消</el-button>
        <el-button  size="small" type="primary" @click="handleSelectBlockConfirm()">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
  import {createSubject, updateSubject,
    getSubject,getBindedProductList,bindProducts,delbindedProducts} from '@/api/homeSubjectNow'
  // import {fetchList, deleteSubjectCategory} from '@/api/homeSubjectNow'
  import {fetchHomeResourceList, fetchResourceDetail, updateHomeResource,deleteHomeResource,fetchRelatedProductList,updateResourceProduct,delRelatedProductList} from '@/api/home-resource'
   import {fetchList as fetchProductList} from '@/api/product';
   import {fetchList as fetchDeptList} from '@/api/depository'
   import {fetchList as fetchBlockList} from '@/api/block';
  import SingleUpload from '@/components/Upload/singleUpload'
  import Tinymce from '@/components/Tinymce'
  import MultiUpload from '@/components/Upload/multiUpload'
  const defaultSubject={
    name: '',
    id:null,
    type:'1',
    picUrl:'',
    productId:null,
    redirectUrl:'',
    subjectId:null,
    productList:[],
    productSingle:[],
    blocks:[],
    sort:null,
  };
  export default {
    name: 'SubjectDetail',
    components:{SingleUpload, MultiUpload, Tinymce},
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        moneyIcon:process.env.MONEY_ICON,
        recommendBlocks:[],//推荐版块
        subject:Object.assign({}, defaultSubject),
        categoryName:'',
        album_pics:null,
        cateOptions:null,
        activeHtmlName: 'pc',
        rules: {
          name: [
            {required: false, message: '请输入名称', trigger: 'blur'},
            {min: 2, max: 140, message: '长度在 2 到 140 个字符', trigger: 'blur'}
          ],
          picUrl: [
            {required: true, message: '请上传图片', trigger: 'blur'}
          ],
          type: [
            {required: true, message: '请选择类型', trigger: 'blur'}
          ],
          sort: [
            {type: 'number', message: '排序必须为数字'}
          ],
           depotId:[
            {required:true, message:'请选择仓库',trigger:"blur"}
          ],
          blocks:[
            {message:'请选择推荐版块',trigger:"blur"}
          ]
        },
        dialogData:{
          list: null,
          total: null,
          multipleSelection:[],
          listQuery:{
            keyword: null,
            pageNum: 1,
            pageSize: 5,
            publishStatus:1,
            verifyStatus:1,
          },
        },
        //productList:[],//商品列表
        depotList:[],//仓库列表
        selectDialogVisible:false,//选择商品的弹窗
        selectBlockDialog:false,//选择专题的弹窗
      }
    },
    computed: {
      //商品的主图和画册图片
      selectProductPics:{
        get:function () {
          let pics=[];
          if(this.albumPics===undefined||this.albumPics==null||this.albumPics===''){
            return pics;
          }
          let albumPics = this.albumPics.split(',');
          for(let i=0;i<albumPics.length;i++){
            pics.push(albumPics[i]);
          }
          return pics;
        },
        set:function (newValue) {
          if (newValue == null || newValue.length === 0) {
            this.albumPics = null;
          } else {
            this.albumPics = '';
            if (newValue.length > 1) {
              for (let i = 1; i < newValue.length; i++) {
                this.albumPics += newValue[i];
                if (i !== newValue.length - 1) {
                  this.albumPics += ',';
                }
              }
            }
          }
        }
      }
    },
    created() {
      // this.getDepotList();
      let self = this;
      if (this.isEdit) {
        fetchResourceDetail(this.$route.query.id).then(response => {
          this.subject =  Object.assign(this.subject,response.data);
          if(this.subject.type ==1 || this.subject.type ==3){
            this.getRelatedProducts();
          }
          if(this.subject.type ==2){
            this.getBlockList('true');
          }
        });
        // getBindedProductList(this.$route.query.id).then(res=>{
        //   if( res.code === 200){
        //     this.subject.productList = res.data;
        //   }else{
        //     this.subject.productList = []
        //   }
        // })
      }else{
        this.subject = Object.assign({},defaultSubject);
         this.subject.blocks =[];
        this.$forceUpdate();
      }
    },
    methods: {
      getBlockList(callback){
        let self = this;
        let listQuery ={
          pageNum: 1,
          pageSize: 50,
        }
        fetchBlockList(self.$route.query.depotId,listQuery).then(response => {
          self.recommendBlocks = response.data.list;
          if(callback && self.subject.type == 2){//推荐版块，编辑状态时要把之前的数据显示出来
            let relatedSubjectId = self.subject.subjectId;
            self.recommendBlocks.map(item=>{
              if(item.id == relatedSubjectId){
                // self.subject.blocks.push(item);
                self.subject.blocks[0] =  item;
              }
            })
          }
        })
      },
      handleSelectProduct(){
        this.selectDialogVisible=true;
        this.getDialogList();
      },
      handleSelectBlock(){
        this.selectBlockDialog=true;
        this.getBlockList();
      },
      handleDeleteBlock(){
        this.subject.blocks = [];
        this.$forceUpdate();
      },
      getDialogList(){
        fetchProductList(this.dialogData.listQuery).then(response=>{
          this.dialogData.list=response.data.list;
          this.dialogData.total=response.data.total;
        })
      },
      handleSelectSearch(){
        this.getDialogList();
      },
      handleDialogSizeChange(val) {
        this.dialogData.listQuery.pageNum = 1;
        this.dialogData.listQuery.pageSize = val;
        this.getDialogList();
      },
      handleDialogCurrentChange(val) {
        this.dialogData.listQuery.pageNum = val;
        this.getDialogList();
      },
      handleDialogSelectionChange(val){
        if(this.subject.type==1){//1，商品详情，只能选择1个商品
          if(val.length>1){
            this.$message({
              message: '只能选择1个商品',
              type: 'warning',
              duration: 1000
            });
            return
          }
        }
        this.dialogData.multipleSelection = val;
        this.$forceUpdate();
      },
      handleBlockDialogSelectionChange(val){
        if(val.length <1)return;
        let isCountinued = true;
        if(this.subject.type==2){//1，商品详情，只能选择1个商品
          if(val.length>1){
            this.$message({
              message: '只能选择1个板块',
              type: 'warning',
              duration: 1000
            });
            isCountinued = false;
            return
          }
        }
        if(isCountinued){
          this.subject.blocks = val;
          this.subject.subjectId = val[0].id;
        }
      },
      
      handleSelectDialogConfirm(){
        if (this.dialogData.multipleSelection < 1) {
          this.$message({
            message: '请选择一条记录',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        if(this.subject.type ==1){
          this.subject.productSingle = this.subject.productSingle.concat(this.dialogData.multipleSelection);
          this.subject.productId = this.subject.productSingle[0].id || null;
        }
        if(this.subject.type ==3){
          this.subject.productList = this.subject.productList.concat(this.dialogData.multipleSelection);
        }
        this.$forceUpdate();
        this.selectDialogVisible = false;//关闭弹窗
      },
      handleSelectBlockConfirm(){
        if (this.subject.blocks.length < 1) {
          this.$message({
            message: '请选择一条记录',
            type: 'warning',
            duration: 1000
          });
          return;
        }
        this.selectBlockDialog = false;//关闭弹窗
      },
      updateResourceProduct(resourcesId){
        let paramsObj={};
        let self = this;
        paramsObj.resourcesId = this.isEdit?this.$route.query.id:resourcesId;
        paramsObj.resourcesRelations = this.subject.type == 3?this.subject.productList:this.subject.productSingle
        
        if(paramsObj && paramsObj.resourcesRelations.length>0){
          paramsObj.resourcesRelations.map(item=>{
            item.productId = item.id;//item.product?item.product.id : item.id;
            item.sort = item.sort;
            item.resourcesId = paramsObj.resourcesId;
            delete item.product
          })
          console.log('关联商品传参');
          console.log(paramsObj);
          updateResourceProduct(paramsObj).then(response=>{
            if(response.code ==200 ){
              self.getRelatedProducts(paramsObj.resourcesId);
            }
          });
        }else{
          return;
        }
      },
      getRelatedProducts(resourcesId){
        let rid = this.$route.query.id?this.$route.query.id:resourcesId;
        fetchRelatedProductList(rid).then(res=>{
          let data = res.data;
          if(data && data.length>0){
            // data.map(item=>{
            //   // item.name = item.product.name;
            //   item.productId = item.product.id;
            // })
            if(this.subject.type == 1){
              this.subject.productSingle = res.data && res.data.length>0?res.data:[];
              this.selectBlockDialog = false;
              this.subject.block=[];
            }
            if(this.subject.type == 3){
              this.subject.productList = res.data && res.data.length>0?res.data:[];
              this.selectDialogVisible= false;
              this.dialogData.multipleSelection=[];
            }
            this.$forceUpdate();
          }else{
            if(this.subject.type == 1){
              this.selectBlockDialog = false;
              this.subject.block=[];
            }
            if(this.subject.type == 3){
              this.selectDialogVisible= false;
              this.dialogData.multipleSelection=[];
            }
          }
        })
      },
      handleDeleteProduct(index,row){
        if(!this.isEdit){//新增状态，可以删除数据
          if(this.subject.type==3){
            let delIdx = this.subject.productList.indexOf(row);
            this.subject.productList.splice(delIdx,1);
          }
          if(this.subject.type ==1){
            this.subject.productSingle = [];
          }
          this.$forceUpdate();
          return;
        }
        let deleteId = row.rid;
        this.$confirm('是否删除商品', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delRelatedProductList(deleteId).then(res=>{
            if(res.code ==200){
              this.$message({
                message: '删除成功',
                type: 'success',
                duration:1000
              });
              this.getRelatedProducts();
            }
          })
        })
      },
      onSubmit(formName) {
        let self = this;
        console.log(self.subject);
        self.$refs[formName].validate((valid) => {
          if (valid) {
            self.$confirm('是否提交数据', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              self.subject.depotId = self.$route.query.depotId;
              //self.subject.id=self.$route.query.id;
              updateHomeResource(self.subject).then(response => {
                if(response.code == 200 && response.data){
                //  if(!self.isEdit){// 非编辑状态时，进行绑定；；编辑状态的话，已经绑定过一次了------>现在因为加了排序字段，所以编辑状态也要保存。。。。
                    if(self.subject.type == 1 || self.subject.type == 3 ){//单个商品 || 商品列表
                      // let paramsObj = {};
                      // paramsObj.resourcesId = response.data;
                      // paramsObj.resourcesRelations = self.subject.type == 3?self.subject.productList:self.subject.productSingle;
                      if(!self.isEdit){
                        self.updateResourceProduct(response.data);
                      }else{
                        self.updateResourceProduct();
                      }
                    }
                //  }
                  
                  self.$refs[formName].resetFields();
                  self.$message({
                    message: '修改成功',
                    type: 'success',
                    duration:1000
                  });
                  self.$router.back();
                }else{
                  self.$message({
                    message:'创建失败。。',
                    type:"warning",
                    duration:2000
                  })
                }
              });
           
            });

          } else {
            self.$message({
              message: '验证失败',
              type: 'error',
              duration:1000
            });
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.subject = Object.assign({},defaultSubject);
      },
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.el-radio--medium.is-bordered{
  padding: 10px 10px 0 5px;
}
</style>